package com.kujie.access.comparator;

import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自然排序
 *
 * @author check
 * @date 2025-06-13
 */
public class NaturalOrderComparator implements Comparator<String> {
    private final Pattern pattern = Pattern.compile("(\\d+)|(\\D+)");

    @Override
    public int compare(String s1, String s2) {
        Matcher m1 = pattern.matcher(s1);
        Matcher m2 = pattern.matcher(s2);

        while (m1.find() && m2.find()) {
            String part1 = m1.group();
            String part2 = m2.group();

            int result;
            if (isDigit(part1) && isDigit(part2)) {
                // 数字部分按数值比较
                result = Long.compare(Long.parseLong(part1), Long.parseLong(part2));
            } else {
                // 非数字部分按字符串比较
                result = part1.compareToIgnoreCase(part2);
            }

            if (result != 0) {
                return result;
            }
        }

        // 如果一方已经匹配完，另一方还有内容，则更长的字符串更大
        return Boolean.compare(m1.hitEnd(), m2.hitEnd());
    }

    private boolean isDigit(String str) {
        return str.matches("\\d+");
    }
}
